<template>
  <el-card shadow="hover">
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="username"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input placeholder="用户昵称" v-model="nickName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList">
          搜索
        </el-button>
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>

    <el-button
      type="primary"
      @click="showAddOrUpdateUser()"
      v-if="userInfoStore.buttons.includes('btn.User.add')"
    >
      添加
    </el-button>
    <el-button
      type="danger"
      :disabled="!selectedUserList.length"
      @click="batchRemoveUserList"
      v-if="userInfoStore.buttons.includes('btn.User.remove')"
    >
      批量删除
    </el-button>

    <el-table
      :data="userList"
      border
      class="mt-20"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60"></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="用户昵称" prop="nickName"></el-table-column>
      <el-table-column label="角色列表" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
      <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button
            type="info"
            size="small"
            :icon="InfoFilled"
            @click="showAssignUserRoleList(row)"
            v-if="userInfoStore.buttons.includes('btn.User.assgin')"
          ></el-button>
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="showAddOrUpdateUser(row)"
            v-if="userInfoStore.buttons.includes('btn.User.update')"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="removeUser(row.id)"
            v-if="userInfoStore.buttons.includes('btn.User.remove')"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-20"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getUserList"
      @current-change="getUserList"
    />

    <!-- 添加或更新用户弹框 -->
    <el-dialog
      v-model="addOrUpdateUserDialogVisible"
      :title="`${userFormData.id ? '更新' : '添加'}用户`"
    >
      <el-form
        label-width="80px"
        ref="userFormRef"
        :model="userFormData"
        :rules="userFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="userFormData.username"
            :disabled="!!userFormData.id"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            placeholder="请输入用户昵称"
            v-model="userFormData.nickName"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入用户密码"
            type="password"
            v-model="userFormData.password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addOrUpdateUserDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="addOrUpdateUser"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配用户角色弹框 -->
    <el-dialog
      v-model="assignUserRoleListDialogVisible"
      title="分配用户角色列表"
    >
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled v-model="userData.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <!-- 
            v-model="checkAll" 全选或全不选
              true 代表全选 false 代表全不选
            :indeterminate="isIndeterminate" 半选状态
              true 代表半选 false 代表没有
           -->
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="userData.roleIdList"
            @change="handleCheckedRoleIdListChange"
          >
            <el-checkbox
              v-for="role in allRoleList"
              :key="role.id"
              :label="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignUserRoleListDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="assignUserRoleList">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Search, InfoFilled, Edit, Delete } from "@element-plus/icons-vue";
import {
  getUserListApi,
  addUserApi,
  updateUserApi,
  removeUserApi,
  batchRemoveUserListApi,
  getRoleByUserIdApi,
  assignUserRoleListApi,
} from "@/api/acl/user";
import type { UserList, UserItem, UserData } from "@/api/acl/models/userModels";
import type { RoleList } from "@/api/acl/models/roleModels";
import { useUserInfoStore } from "@/stores/userInfo";

defineOptions({
  name: "User",
});

// 7. 按钮权限控制
const userInfoStore = useUserInfoStore();

// 6. 分配用户角色列表
const assignUserRoleListDialogVisible = ref(false);

const userData = reactive<UserData>({
  userId: "",
  roleIdList: [],
  username: "",
});

const allRoleList = ref<RoleList>([]);

const showAssignUserRoleList = async (row: UserItem) => {
  assignUserRoleListDialogVisible.value = true;
  userData.userId = row.id as string;
  userData.username = row.username;
  // 清空数据
  userData.roleIdList = [];
  isIndeterminate.value = false;
  checkAll.value = false;

  const res = await getRoleByUserIdApi(row.id as string);
  allRoleList.value = res.allRolesList;
  userData.roleIdList = res.assignRoles.map((role) => role.id); // 只需要id参数
  // 判断是全选还是半选还是全不选
  handleCheckedRoleIdListChange(userData.roleIdList);
};

const checkAll = ref(false); // 全选
const isIndeterminate = ref(false); // 半选

const handleCheckAllChange = (val: any) => {
  isIndeterminate.value = false;

  if (val) {
    // 全选：需要所有id
    userData.roleIdList = allRoleList.value.map((role) => role.id);
  } else {
    // 全不选：清空
    userData.roleIdList = [];
  }
};

const handleCheckedRoleIdListChange = (val: any) => {
  if (val.length === allRoleList.value.length) {
    // 全选
    checkAll.value = true;
    isIndeterminate.value = false;
  } else if (val.length === 0) {
    // 全不选
    checkAll.value = false;
    isIndeterminate.value = false;
  } else {
    // 半选
    isIndeterminate.value = true;
  }
};

const assignUserRoleList = async () => {
  await assignUserRoleListApi(userData.userId, userData.roleIdList);
  ElMessage.success("分配用户角色列表成功");
  assignUserRoleListDialogVisible.value = false;
  getUserList();
};

// 5. 批量删除
const selectedUserList = ref<UserList>([]);
const handleSelectionChange = (rows: UserList) => {
  selectedUserList.value = rows;
};

const batchRemoveUserList = async () => {
  const idList = selectedUserList.value.map((user) => user.id as string);
  await batchRemoveUserListApi(idList);
  ElMessage.success("批量删除用户成功");
  getUserList();
  selectedUserList.value = [];
};

// 4. 单个删除
const removeUser = async (id: string) => {
  await removeUserApi(id);
  ElMessage.success("删除用户成功");
  getUserList();
};

// 3. 添加或更新用户
const addOrUpdateUserDialogVisible = ref(false);

// const showAddUser = () => {
//   addOrUpdateUserDialogVisible.value = true;
//   userFormData.username = "";
//   userFormData.nickName = "";
//   userFormData.password = "";
//   userFormRef.value?.clearValidate();
// };

// const showUpdateUser = (row: UserItem) => {
//   addOrUpdateUserDialogVisible.value = true;
//   userFormData.username = row.username;
//   userFormData.nickName = row.nickName;
//   userFormData.password = row.password;
//   userFormRef.value?.clearValidate();
// };

const showAddOrUpdateUser = (
  row: UserItem = { nickName: "", username: "", password: "", id: "" }
) => {
  addOrUpdateUserDialogVisible.value = true;
  userFormData.username = row.username;
  userFormData.nickName = row.nickName;
  userFormData.password = "";
  userFormData.id = row.id;
  userFormRef.value?.clearValidate();
};

const userFormRef = ref();

const userFormData = reactive<UserItem>({
  id: "",
  username: "",
  nickName: "",
  password: "",
});

const userFormRules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  nickName: [
    {
      required: true,
      message: "请输入用户昵称",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});

const addOrUpdateUser = async () => {
  await userFormRef.value.validate();

  const id = userFormData.id;

  if (id) {
    await updateUserApi(userFormData);
  } else {
    await addUserApi(userFormData);
  }

  ElMessage.success(`${id ? "更新" : "添加"}用户成功`);
  getUserList();
  addOrUpdateUserDialogVisible.value = false;
};

// 2. 搜索&清空功能
const username = ref("");
const nickName = ref("");

const reset = () => {
  username.value = "";
  nickName.value = "";

  getUserList();
};

// 1. 获取用户列表展示
const userList = ref<UserList>([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const loading = ref(false);

const getUserList = async () => {
  loading.value = true;
  const res = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
    nickName: nickName.value,
  });
  userList.value = res.items;
  total.value = res.total;
  loading.value = false;
};

onMounted(getUserList);
</script>

<style scoped lang="scss"></style>
